package cn.com.mall.product.service.impl;

import cn.com.mall.common.utils.PageUtils;
import cn.com.mall.common.utils.Query;
import cn.com.mall.product.dao.AttrAttrgroupRelationDao;
import cn.com.mall.product.dao.AttrDao;
import cn.com.mall.product.dao.AttrGroupDao;
import cn.com.mall.product.dao.CategoryDao;
import cn.com.mall.product.entity.AttrAttrgroupRelationEntity;
import cn.com.mall.product.entity.AttrEntity;
import cn.com.mall.product.entity.AttrGroupEntity;
import cn.com.mall.product.entity.CategoryEntity;
import cn.com.mall.product.service.AttrService;
import cn.com.mall.product.service.CategoryService;
import cn.com.mall.product.vo.AttrResVo;
import cn.com.mall.product.vo.AttrVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    public AttrAttrgroupRelationDao relationDao;

    @Autowired
    public AttrGroupDao attrGroupDao;

    @Autowired
    public CategoryDao categoryDao;
    @Autowired
    public CategoryService categoryService;
    @Autowired
    public AttrDao attrDao;

    @Autowired
    public AttrAttrgroupRelationServiceImpl relationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void save(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //保存基本数据
        this.save(attrEntity);

        if(attr.getAttrType()==1) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());

            relationDao.insert(relationEntity);
        }

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, Long attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", attrType);
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((item) -> {
                item.like("attr_name", key).or().like("attr_id", key);
            });
        }

        if (catelogId != 0) {

            queryWrapper.eq("catelog_id", catelogId);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params), queryWrapper

        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrResVo> respVos = page.getRecords().stream().map(item -> {
            AttrResVo resVo = new AttrResVo();
            BeanUtils.copyProperties(item, resVo);

            if(attrType==1) {
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
                if (relationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        resVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());
            if (categoryEntity != null) {
                resVo.setCatelogName(categoryEntity.getName());
            }

            return resVo;

        }).collect(Collectors.toList());

        pageUtils.setList(respVos);
        return pageUtils;

    }

    @Override
    public AttrResVo getAttrInfoById(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrResVo resVo = new AttrResVo();
        BeanUtils.copyProperties(attrEntity, resVo);

        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());

        resVo.setCatelogPath(catelogPath);

        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrId));
        if (relationEntity != null) {
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            resVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
            resVo.setGroupName(attrGroupEntity.getAttrGroupName());
        }

        return resVo;

    }

    @Override
    @Transactional
    public void updateAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);

        this.updateById(attrEntity);
        if(attr.getAttrType()==1) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attr, relationEntity);
            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                relationDao.update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                relationEntity.setAttrId(attr.getAttrId());

                relationDao.insert(relationEntity);
            }
        }


    }

    @Override
    public PageUtils noattrRelation(Map<String, Object> params, String attrgroupId) {
        //当前分组只能关联自己所属分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //当前分组只能关联分组没有饮用的属性

        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIdList = attrGroupEntities.stream().map(item ->
                item.getAttrGroupId()
        ).collect(Collectors.toList());

        //根据关联关系找出来已经关联的属性。
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper=new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id",groupIdList);

        List<AttrAttrgroupRelationEntity> relationEntities = relationService.getBaseMapper().selectList(wrapper);

        List<Long> collect = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());

        //
        QueryWrapper<AttrEntity> attrEntityQueryWrapper=new QueryWrapper<AttrEntity>().eq("catelog_id",catelogId).eq("attr_type","1");
        if(collect!=null && collect.size()>0){
            attrEntityQueryWrapper.notIn("attr_id",collect);
        }


        IPage<AttrEntity> attrEntityIPage = getBaseMapper().selectPage(new Query<AttrEntity>().getPage(params), attrEntityQueryWrapper);

        PageUtils pageUtils = new PageUtils(attrEntityIPage);

        List<AttrVO> attrVOS = attrEntityIPage.getRecords().stream().map(item -> {
            AttrVO attrVO = new AttrVO();
            BeanUtils.copyProperties(item, attrVO);
            return attrVO;
        }).collect(Collectors.toList());

        pageUtils.setList(attrVOS);

        return pageUtils;
    }

    @Override
    public List<Long> selectSerchAttrIds(List<Long> attrIds) {
        List<AttrEntity> entities = this.baseMapper.selectBatchIds(attrIds);
        List<Long> list = entities.stream().filter(
                item -> item.getSearchType() == 1

        ).map(attr -> attr.getAttrId()).collect(Collectors.toList());
        return list;
    }

    /**
     * 根据分组id找到属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> collect = relationEntities.stream().map(
                item -> item.getAttrId()
        ).collect(Collectors.toList());

        if(collect!=null && collect.size()>0){
            return this.listByIds(collect);
        }

        return null;


    }



}